# Skripta ki skrbi za povezavo s ASYS
import sys
import System
import System.Threading
import clr
import time
import threading
import thread
import ee3
import ee3_gui

clr.AddReference('System')
clr.AddReference('System.Windows.Forms')
from System.ComponentModel import BackgroundWorker
clr.AddReferenceByPartialName('MySql.Data')
from MySql.Data.MySqlClient import *
from System.Collections import *
from System.Threading import *

# FUNKCIJE
stevec_poizvedb = 0
class ObjectLocker(object):
      def __init__(self, obj):
              self.obj = obj
      def __enter__(self):
              global stevec_poizvedb
              stevec_poizvedb += 1
              Monitor.Enter(self.obj)
      def __exit__(self, *args):
              global stevec_poizvedb
              stevec_poizvedb -= 1
              Monitor.Exit(self.obj)

#
# Poizvedba na ASYS
#
conStrNtpe1 = 'server=ntpe1; userid=purkat; password=purkat; database=sledljivost;'
def poizvedbaNTPE(stavek, izhod):
    dbNtpe1 = MySqlConnection(conStrNtpe1)
    l = ArrayList()
    i=0
    print("ASYS: %s" %stavek)
    with ObjectLocker(dbNtpe1):
        ee3_gui.barva_obrazca('Blue')
        while dbNtpe1.State.ToString() != "Open":  
            try:
              dbNtpe1.Open()
              cmd = dbNtpe1.CreateCommand()
              cmd.CommandText = stavek
              r = cmd.ExecuteReader ()
              l = ArrayList()
              while r.Read ():
                  vrednost = izhod
                  for x in range(r.FieldCount):
                      vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                  l.Add(vrednost)
              r.Close ()
              ee3_gui.barva_obrazca('None')
            except Exception as e:
              debug.TraceDbg("Povezava na ASYS neuspesna!", e.message.ToString(), "Warning")
              System.Threading.Thread.Sleep(2000)
              if (i<2):
                ee3_gui.barva_obrazca('Orange')
              else:
                ee3_gui.barva_obrazca('Red')
              i=i+1
        dbNtpe1.Close ()
        return l

def bg_Poizvedba_NTPE(sender, args):
    tmp = poizvedbaNTPE(args.Argument[0], args.Argument[1])
    args.Result = [tmp, args.Argument[2]]


def dopolni(combobox, stavek, struktura, opis):
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_NTPE
    worker.RunWorkerCompleted += bg_dopolni_completed
    combobox.ItemsSource = None
   # obrazec.label_status.Content = opis
    worker.RunWorkerAsync([stavek, struktura, combobox])

def bg_dopolni_completed(sender, args):
   # obrazec.label_status.Content = ''
    if (args.Result[0] != None):
        args.Result[1].ItemsSource = args.Result[0]

def izberi(combobox, stavek, struktura, opis):
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_NTPE
    worker.RunWorkerCompleted += bg_izberi_completed
    spremenljivka = None
    worker.RunWorkerAsync([stavek, struktura, combobox])

def bg_izberi_completed(sender, args):
   # obrazec.label_status.Content = ''
    if (args.Result[0].Count == 1):
        args.Result[1].SelectedItem = args.Result[0][0]
    else:
        args.Result[1].SelectedItem = None


def seznam(lista, stavek, struktura, opis):
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_NTPE
    worker.RunWorkerCompleted += bg_seznam_completed
    lista = None
    worker.RunWorkerAsync([stavek, struktura, lista])

def bg_seznam_completed(sender, args):
   # obrazec.label_status.Content = ''
    if (args.Result[0] != None):
        if (type(args.Result[0]) != str):
            print("Rezultati iz ASYSa za nalog (%s kosov)" %(args.Result[0].Count))
            for i in range(args.Result[0].Count):
                print("%s" %(args.Result[0][i]))
    ee3.ProcesneSerijske_ASYS = args.Result[0]
   #ee3.printseznam()